package com.ssm.sport.controller;

import com.ssm.sport.entity.Banner;
import com.ssm.sport.entity.Category;
import com.ssm.sport.entity.Product;
import com.ssm.sport.service.BannerService;
import com.ssm.sport.service.CategoryService;
import com.ssm.sport.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import javax.servlet.http.HttpSession;

/**
 * 首页控制器
 */
@Controller
public class IndexController {

    @Autowired
    private ProductService productService;
    
    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private BannerService bannerService;
    
    /**
     * 首页
     */
    @GetMapping(value = {"", "/", "/index"})
    public String index(Model model) {
        // 获取热门商品
        List<Product> hotProducts = productService.getHotProducts(6);
        //重新刷洗图片路径问题
        for (Product product : hotProducts) {
            product.setMainImage("/sport_mall_war"+product.getMainImage());
        }
        model.addAttribute("hotProducts", hotProducts);
        
        // 获取新品
        List<Product> newProducts = productService.getNewProducts(8);
        for (Product product : newProducts) {
            product.setMainImage("/sport_mall_war"+product.getMainImage());
        }
        model.addAttribute("newProducts", newProducts);
        
        // 获取所有一级分类
        List<Category> categories = categoryService.getTopCategories();
        for (Category category : categories) {
            category.setImage("/sport_mall_war"+category.getImage());
        }
        model.addAttribute("categories", categories);
        
        // 获取轮播图数据
        List<Banner> banners = bannerService.listEnabledBanners();
        banners.forEach(banner -> {
            banner.setImageUrl("/sport_mall_war"+banner.getImageUrl());
        });
        model.addAttribute("banners", banners);
        
        return "index";
    }

    // Check if file exists or create it
    // Add method for view-based logout that redirects to homepage
    
    /**
     * 退出登录 (视图版)
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/index";
    }
} 